import asyncio
import time
import os
from feishu import feishu_api
from eccang import call_eccang

from log_case import do_something

import logging
from logging_config import setup_logger  # 导入但无需调用
logger = logging.getLogger(__name__)

from config import config_xxl_job

from pyxxl import ExecutorConfig, PyxxlRunner
from pyxxl.ctx import g

os.makedirs(config_xxl_job["log_local_dir"], exist_ok=True)
logger.info("==============================makedirs")

# 如果xxl-admin可以直连executor的ip，可以不填写executor_listen_host
config = ExecutorConfig(
    xxl_admin_baseurl = config_xxl_job["xxl_admin_baseurl"],
    executor_app_name = config_xxl_job["executor_app_name"],
    executor_listen_host = config_xxl_job["executor_listen_host"],  # xxl-admin监听时绑定的host,默认为第一个网卡地址
    access_token = config_xxl_job["access_token"],  # xxl-admin的access_token
    log_local_dir = config_xxl_job["log_local_dir"],
    executor_log_path = config_xxl_job["executor_log_path"],
    debug = config_xxl_job["debug"],
)

app = PyxxlRunner(config)

# 注册任务：函数方式
app.register(call_eccang.save_eccang_data_to_feishu, name="save_eccang_data_to_feishu")

# 注册任务：注解方式
@app.register(name="demoJobHandler")
@app.register(name="demoJobHandler2")
async def test_task():
    # you can get task params with "g"
    g.logger.info("get executor params: %s" % g.xxl_run_data.executorParams)
    for i in range(10):
        g.logger.warning("test logger %s" % i)
    await asyncio.sleep(5)
    return "成功..."


@app.register(name="test_task2")
async def test_task3():
    logger.info("==============================")
    g.logger.info("exec test_task2 start")
    await asyncio.sleep(30)
    g.logger.info("exec test_task2 end")
    logger.info("==============================")
    return "成功3"


@app.register(name="sync_func")
def test_task4():
    # 如果要在xxl-admin上看到执行日志，打印日志的时候务必用g.logger来打印，默认只打印info及以上的日志
    n = 1
    g.logger.info("Job %s get executor params: %s" % (g.xxl_run_data.jobId, g.xxl_run_data.executorParams))
    # 如果同步任务里面有循环，为了支持cancel操作，必须每次都判断g.cancel_event.
    while n <= 10 and not g.cancel_event.is_set():
        # 如果不需要从xxl-admin中查看日志，可以用自己的logger
        g.logger.info(
            "log to {} logger test_task4.{},params:{}".format(
                g.xxl_run_data.jobId,
                n,
                g.xxl_run_data.executorParams,
            )
        )
        time.sleep(2)
        n += 1
    return "成功3"


if __name__ == "__main__":
    do_something()
    app.run_executor()
